import React from 'react'
import * as Icon from '@ant-design/icons'
import { Button, Layout, Menu, theme } from 'antd'
import MenuConfig from '../../config/index'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { setMenuList } from '../../store/reducers/tab'
const { Header, Sider, Content } = Layout
// 动态获取icon
const iconToElement = (item) => React.createElement(Icon[item])
// 处理菜单数据
const Menuitems = MenuConfig.map((item) => {
  // 没有子菜单
  const child = {
    key: item.path,
    icon: iconToElement(item.icon),
    label: item.label
  }
  if (item.children) {
    child.children = item.children.map((items) => {
      return {
        key: items.path,
        label: items.label
      }
    })
  }
  return child
})
const CommonAside = ({ collapsed }) => {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  // 点击菜单事件
  const selectMenu = (e) => {
    let data
    MenuConfig.forEach((item) => {
      if (item.path == e.keyPath[e.keyPath.length - 1]) {
        data = item
        if (e.keyPath.length > 1) {
          data = item.children.find((child) => {
            return child.path == e.key
          })
        }
      }
    })
    dispatch(
      setMenuList({
        path: data.path,
        name: data.name,
        label: data.label
      })
    )

    navigate(e.key)
  }
  return (
    <Sider trigger={null} collapsed={collapsed}>
      <h3 className="app-name"> {collapsed ? '后台' : '后台管理系统'}</h3>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={['1']}
        items={Menuitems}
        style={{
          height: '100%'
        }}
        onClick={selectMenu}
      />
    </Sider>
  )
}

export default CommonAside
